package com.longge;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-04-29 02:55
 */
public class AverageOfLevels {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Double doubleValue = 0.0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                doubleValue += node.val;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            res.add(doubleValue / size);
        }
        return res;
    }
}
